package com.jfinal.core;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;

import com.jfinal.config.Constants;
import com.jfinal.log.Logger;
import com.jfinal.render.Render;
import com.jfinal.render.RenderException;
import com.jfinal.render.RenderFactory;
import com.jfinal.spring.AbstractSpringHandler;

/**
 * 参照 ActionHandler
 * @ClassName: SpringHandler
 * @author huangx
 * @date 2015年1月28日 上午11:32:24
 */
public class SpringHandler extends AbstractSpringHandler {
	private final boolean devMode;
	private final ActionMapping actionMapping;
	private static final RenderFactory renderFactory = RenderFactory.me();
	private static final Logger log = Logger.getLogger(SpringHandler.class);

	public SpringHandler(ActionMapping actionMapping, Constants constants, ApplicationContext ctx) {
		super(ctx);
		this.actionMapping = actionMapping;
		this.devMode = constants.getDevMode();
	}

	/**
	 * handle
	 * 1: Action action = actionMapping.getAction(target)
	 * 2: new ActionInvocation(...).invoke()
	 * 3: render(...)
	 */
	public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
		if (target.indexOf('.') != -1) { return; }

		isHandled[0] = true;
		String[] urlPara = { null };

		// 获得 Action , 加载 actionMapping
		Action action = actionMapping.getAction(target, urlPara);

		if (action == null) {
			if (log.isWarnEnabled()) {
				String qs = request.getQueryString();
				log.warn("404 Action Not Found: " + (qs == null ? target : target + "?" + qs));
			}
			renderFactory.getErrorRender(404).setContext(request, response).render();
			return;
		}

		try {
			// 获得 Controller
			Controller controller = super.getController(action.getControllerClass());
			controller.init(request, response, urlPara[0]);

			if (devMode) {
				boolean isMultipartRequest = ActionReporter.reportCommonRequest(controller, action);
				new ActionInvocation(action, controller).invoke();
				if (isMultipartRequest) ActionReporter.reportMultipartRequest(controller, action);
			} else {
				new ActionInvocation(action, controller).invoke();
			}

			Render render = controller.getRender();
			if (render instanceof ActionRender) {
				String actionUrl = ((ActionRender) render).getActionUrl();
				if (target.equals(actionUrl)) throw new RuntimeException("The forward action url is the same as before.");
				else handle(actionUrl, request, response, isHandled);
				return;
			}

			if (render == null) render = renderFactory.getDefaultRender(action.getViewPath() + action.getMethodName());
			render.setContext(request, response, action.getViewPath()).render();
		} catch (RenderException e) {
			if (log.isErrorEnabled()) {
				String qs = request.getQueryString();
				log.error(qs == null ? target : target + "?" + qs, e);
			}
		} catch (ActionException e) {
			int errorCode = e.getErrorCode();
			if (errorCode == 404 && log.isWarnEnabled()) {
				String qs = request.getQueryString();
				log.warn("404 Not Found: " + (qs == null ? target : target + "?" + qs));
			} else if (errorCode == 401 && log.isWarnEnabled()) {
				String qs = request.getQueryString();
				log.warn("401 Unauthorized: " + (qs == null ? target : target + "?" + qs));
			} else if (errorCode == 403 && log.isWarnEnabled()) {
				String qs = request.getQueryString();
				log.warn("403 Forbidden: " + (qs == null ? target : target + "?" + qs));
			} else if (log.isErrorEnabled()) {
				String qs = request.getQueryString();
				log.error(qs == null ? target : target + "?" + qs, e);
			}
			e.getErrorRender().setContext(request, response).render();
		} catch (Throwable t) {
			if (log.isErrorEnabled()) {
				String qs = request.getQueryString();
				log.error(qs == null ? target : target + "?" + qs, t);
			}
			renderFactory.getErrorRender(500).setContext(request, response).render();
		}
	}
}
